package com.huang.untils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.google.gson.Gson;
import com.huang.entity.ListType;
import com.huang.entity.RecommendProduct;
import com.huang.mapper.*;
import org.jsoup.Connection;

import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class PupuCrawler {

    private final RecommendProduct temp = new RecommendProduct();

    private DiscountProductMapper discountProductMapper;

    private SingleProductMapper singleProductMapper;

    private RecommendProductMapper productMapper;

    private ListTypeMapper listTypeMapper;

    private BaseMapper baseMapper;


    @Autowired
    public void setListTypeMapper(ListTypeMapper listTypeMapper) {
        this.listTypeMapper = listTypeMapper;
    }

    @Autowired
    public void setDiscountProductMapper(DiscountProductMapper discountProductMapper) {
        this.discountProductMapper = discountProductMapper;
    }

    @Autowired
    public void setSingleProductMapper(SingleProductMapper singleProductMapper) {
        this.singleProductMapper = singleProductMapper;
    }

    @Autowired
    public void setProductMapper(RecommendProductMapper productMapper) {
        this.productMapper = productMapper;
    }

    public ReStates contextLoads(String type) {
        Connection.Response response = null;

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("name", type);


        List<ListType> listTypes = listTypeMapper.selectByMap(queryMap);

        if (listTypes == null||listTypes.get(0)==null) {
            return new ReStates().updateFalse();
        }

        String url = listTypes.get(0).getUrl();
        if (url == null) {
            return new ReStates().isFalse();
        }

        try {
            response = Jsoup.connect(url)
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .userAgent("Mozilla/5.0 (Linux; Android 10; SM-G981B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Mobile Safari/537.36")
                    .header("Accept-Encoding", "gzip, deflate, br")
                    .ignoreContentType(true)
                    .execute();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (response == null) {
            return new ReStates().updateFalse();
        }
        Gson gson = new Gson();

        @SuppressWarnings("unchecked")
        Map<Object, Object> json = gson.fromJson(response.body(), HashMap.class);
        @SuppressWarnings("unchecked")
        Map<Object, Object> data = (Map<Object, Object>) json.get("data");
        @SuppressWarnings("unchecked")
        List<Map<Object, Object>> map = (List<Map<Object, Object>>) data.get("products");

        selectType(type);
        map.forEach(this::showdata);


        return new ReStates().isOK();
    }

    void showdata(Map<Object, Object> map) {

        String product_id = (String) map.get("product_id");

        temp.setProductId(product_id);
        if (baseMapper.exists(new QueryWrapper<>(temp))) {
            RecommendProduct recommendProduct = constructObjcet(map);
            System.out.println("更新"+recommendProduct);
            baseMapper.updateById(recommendProduct);
        } else {
            RecommendProduct recommendProduct = constructObjcet(map);
            System.out.println("插入"+recommendProduct);
            baseMapper.insert(recommendProduct);
        }

    }

    private RecommendProduct constructObjcet(Map<Object, Object> map) {
        String product_id = (String) map.get("product_id");
        String name = (String) map.get("name");
        Double market_price = (Double) map.get("market_price");
        Double price = (Double) map.get("price");
        Double discount_rate = (Double) map.get("discount_rate");
        String sub_title = (String) map.get("sub_title");
        String spec = (String) map.get("spec");
        String origin = (String) map.get("origin");

        return new RecommendProduct(product_id, name, price, market_price, discount_rate, sub_title, spec, origin, LocalDateTime.now());
    }

    private void selectType(String type) {
        switch (type) {
            case "Recommend":
                baseMapper = productMapper;
                break;
            case "Discount":
                baseMapper = discountProductMapper;
                break;
            case "Single":
                baseMapper = singleProductMapper;
                break;
        }

    }
}


